package cn.wildfirechat.message.notification;

import android.os.Parcel;
import android.util.Log;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import cn.wildfirechat.message.Message;
import cn.wildfirechat.message.core.ContentTag;
import cn.wildfirechat.message.core.MessagePayload;
import cn.wildfirechat.message.core.PersistFlag;
import cn.wildfirechat.model.GroupMember;
import cn.wildfirechat.model.UserInfo;
import cn.wildfirechat.remote.ChatManager;

import static cn.wildfirechat.message.core.MessageContentType.MESSAGE_CONTENT_TYPE_SET_GROUP_MEMBER_SILENCE;

/**
 * Create by HEKE, 2019/10/10 21:05
 * TODO 个人禁言消息接收对象
 */
@ContentTag(type = MESSAGE_CONTENT_TYPE_SET_GROUP_MEMBER_SILENCE, flag = PersistFlag.Persist)
public class SingleSilenceGroupNotificationContent extends GroupNotificationMessageContent {

    public String operator;
    public int silence;
    public String useridlist;
    protected List<UserInfo> beopratorUserInfoList;
    private boolean isSilence;

    public SingleSilenceGroupNotificationContent() {
    }

    @Override
    public String formatNotification(Message message) {
        isSilence = (silence == 1);
        StringBuilder sb = new StringBuilder();
        try {
            if (useridlist != null && useridlist.trim().length() > 0) {
                beopratorUserInfoList = new ArrayList<>();
                JSONArray jsonArray = new JSONArray(useridlist);
                for (int i = 0; i < jsonArray.length(); i++) {
                    String userId = jsonArray.getString(i);
                    UserInfo userInfo = ChatManager.Instance().getUserInfo(userId, groupId, false);
                    beopratorUserInfoList.add(userInfo);
                }
            }
            if (fromSelf) {
                if (isSilence) {
                    setOpratorString(beopratorUserInfoList, sb);
                    sb.append("已禁言");
                } else {
                    setOpratorString(beopratorUserInfoList, sb);
                    sb.append("已解除禁言");
                }
            } else {
                UserInfo groupOnwerUserInfo = ChatManager.Instance().getUserInfo(operator, groupId, false);
                // 自身是被执行人
                if (isSelfBeingOporator()) {
                    if (isSilence) {
                        if (beopratorUserInfoList.size() > 1) {
                            sb.append("你已被" + groupOnwerUserInfo.displayName + "禁言");
                        } else {
                            sb.append("你已被" + groupOnwerUserInfo.displayName + "禁言");
                        }
                    } else {
                        sb.append("你已被" + groupOnwerUserInfo.displayName + "解除禁言");
                    }
                } else {
                    // 其他人设置
                    if (isSilence) {
                        setOpratorString(beopratorUserInfoList, sb);
                        sb.append("已被" + groupOnwerUserInfo.displayName + "禁言");
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sb.toString();
    }

    /**
     * 设置多账户文本显示
     *
     * @param beopratorUserInfoList
     * @param sb
     */
    private void setOpratorString(List<UserInfo> beopratorUserInfoList, StringBuilder sb) {
        try {
            if (beopratorUserInfoList != null && beopratorUserInfoList.size() > 0) {
                for (int i = 0; i < beopratorUserInfoList.size(); i++) {
                    UserInfo userInfo = beopratorUserInfoList.get(i);
                    String groupDisplayName = ChatManager.Instance().getGroupMemberDisplayName(groupId, userInfo.uid);
                    if (i == beopratorUserInfoList.size() - 1) {
                        sb.append(groupDisplayName + " ");
                    } else {
                        sb.append(groupDisplayName + "，");
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 判断自身是否是被执行的成员
     */
    private boolean isSelfBeingOporator() {
        if (beopratorUserInfoList == null || beopratorUserInfoList.size() == 0) {
            return false;
        }
        String selfUserId = ChatManager.Instance().getUserId();
        for (UserInfo userInfo : beopratorUserInfoList) {
            if (selfUserId.equals(userInfo.uid)) {
                return true;
            }
        }
        return false;
    }

    @Override
    public MessagePayload encode() {
        MessagePayload payload = new MessagePayload();

        try {
            JSONObject objWrite = new JSONObject();
            objWrite.put("g", groupId);
            objWrite.put("o", operator);
            objWrite.put("n", silence);
            objWrite.put("m", useridlist);
            payload.binaryContent = objWrite.toString().getBytes();
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return payload;
    }

    @Override
    public void decode(MessagePayload payload) {
        try {
            if (payload.content != null) {
                JSONObject jsonObject = new JSONObject(new String(payload.binaryContent));
                groupId = jsonObject.optString("g");
                operator = jsonObject.optString("o");
                silence = jsonObject.optInt("n");
                useridlist = jsonObject.optString("ms");
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }


    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(this.operator);
        dest.writeString(this.groupId);
        dest.writeByte(this.fromSelf ? (byte) 1 : (byte) 0);
        dest.writeInt(this.mentionedType);
        dest.writeStringList(this.mentionedTargets);
        dest.writeString(this.useridlist);
        dest.writeInt(this.silence);
    }

    protected SingleSilenceGroupNotificationContent(Parcel in) {
        this.operator = in.readString();
        this.groupId = in.readString();
        this.fromSelf = in.readByte() != 0;
        this.mentionedType = in.readInt();
        this.mentionedTargets = in.createStringArrayList();
        this.useridlist = in.readString();
        this.silence = in.readInt();
    }

    public static final Creator<SingleSilenceGroupNotificationContent> CREATOR = new Creator<SingleSilenceGroupNotificationContent>() {
        @Override
        public SingleSilenceGroupNotificationContent createFromParcel(Parcel source) {
            return new SingleSilenceGroupNotificationContent(source);
        }

        @Override
        public SingleSilenceGroupNotificationContent[] newArray(int size) {
            return new SingleSilenceGroupNotificationContent[size];
        }
    };

}
